package cn.dylan.org.service.impl;

import cn.dylan.basic.service.impl.BaseServiceImpl;
import cn.dylan.org.domain.Department;
import cn.dylan.org.mapper.DepartmentMapper;
import cn.dylan.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService{

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public void save(Department department) {

        // 做dirPath  已返回主键ID
        departmentMapper.save(department);

        /*// parent_id为空和不为空两种情况
        if(department.getParent_id()==null){ // 本身为定级部门 dirPath 为其本身
            department.setDirPath("/" + department.getId());
        }else{ // 本身不为顶级部门 那么其dirPath为其上级部门dirPath+其本身id
            Department parentDept = departmentMapper.LoadById(department.getParent_id());
            department.setDirPath(parentDept.getDirPath()+"/"+department.getId());
        }
        // 更新dirPath
        departmentMapper.update(department);*/

        // 会调用update update里面会做以上所有操作，所以只需要update
        departmentMapper.update(department);

    }

    @Override
    public void update(Department department) {
        departmentMapper.update(department);

        if(department.getParent_id()==null){ // 本身为定级部门 dirPath 为其本身
            department.setDirPath("/" + department.getId());
        }else{ // 本身不为顶级部门 那么其dirPath为其上级部门dirPath+其本身id
            Department parentDept = departmentMapper.LoadById(department.getParent_id());
            department.setDirPath(parentDept.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }


    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();

        HashMap<Long, Department> map = new HashMap<>();

        for (Department department : departments) {
            map.put(department.getId(),department);
        }
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id()==null){
                deptTree.add(department);
            }else{
                // 根据parent_id 获取上级部门对象
                Long parent_id = department.getParent_id();
                Department parentDepartment = map.get(parent_id);
                // 把当前非顶级部门对象放入其上级部门对应的子集部门中
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
